/*
 * 文件名称: ObjSqlFactory.java
 * 版权信息: Copyright 2001-2012 ZheJiang Collaboration Data System Co., LTD. All right reserved.
 * ----------------------------------------------------------------------------------------------
 * 修改历史:
 * ----------------------------------------------------------------------------------------------
 * 修改原因: 新增
 * 修改人员: huangwb
 * 修改日期: 2012-3-1
 * 修改内容: 
 */
package com.huangwb.person.source.sqlfile;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import uk.ltd.getahead.dwr.util.Logger;

import com.huangwb.person.bean.ArgInfo;
import com.huangwb.person.bean.Column;
import com.huangwb.person.bean.Obj;
import com.huangwb.person.source.DefaultObjFactory;
import com.huangwb.person.source.ObjFactory;


/**
 * 
 * @author <a href="mailto:huangwb@zjcds.com">huangwb</a> created on 2012-3-1
 * @since DE6.0
 */
public class ObjSqlFactory implements ObjFactory {
    
    Logger logger = Logger.getLogger(getClass());
    
    private static String PRIMARYKEY = "PRIMARY KEY";
    private static String FOREIGNKEY = "FOREIGN KEY";
    
    @Override
    public Obj getObj(ArgInfo argInfo) {
        String filePath = argInfo.getSqlFilePath();
        
        BufferedReader br = SqlFileReadHelper.readSql(filePath);
        String sql = "";
        try {
            sql = SqlFileReadHelper.readSql(br);
        }
        catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("末获取到表名称",e);
        }
        
        String tableName = captureTableName(sql);
        if (StringUtils.isNotBlank(tableName)) {
            argInfo.setTableName(tableName);
        }
        List<Column> columns = parseSql(sql);
        
        return new DefaultObjFactory().genObj(argInfo, columns);
    }

    
    
    private List<Column> parseSql(String sql) {
        List<Column> props = new ArrayList<Column>();
        String fbracket = "(";
        String lbracket = ")";
        int fBracketPos = 0;
        int lBracketPos = 0;
        fBracketPos = sql.indexOf(fbracket);
        lBracketPos = sql.lastIndexOf(lbracket);
        String subStr = sql.substring(fBracketPos+1,lBracketPos);
        String[] lines = subStr.split(",");
        String[] temps = null;
        Boolean isPrimary = false;
        String primaryKey = capturePrimarykey(subStr);
        for (String line : lines) {
            isPrimary = false;
            line = line.trim();
            if(line.toUpperCase().contains(PRIMARYKEY) && line.endsWith(",")) {
                isPrimary = true;
            } else if(line.toUpperCase().contains(PRIMARYKEY) || line.toUpperCase().contains(FOREIGNKEY)) {
                continue;
            }
            temps = line.split(" ");
            if(temps.length > 1) {
                if (primaryKey.toUpperCase().contains(temps[0].toUpperCase())) {
                    isPrimary = true;
                }
                props.add(new Column(temps[0],temps[1].replaceAll("\\(.*?\\)", ""),isPrimary));
            } 
        }
        return props;
    }
    /**
     * 获取主键
     * 
     * @param line
     * @return
     */
    private String capturePrimarykey(String line) {
        line = line.trim();
        if(line.toUpperCase().contains(PRIMARYKEY)) {
        	int start = line.toUpperCase().indexOf(PRIMARYKEY)+PRIMARYKEY.length();
        	int end = line.indexOf(",", start);
        	//start and end to capture the primary key line
        	if (end > 0) {
        		return line.substring(start,end);
        	}
        	return line.substring(start);
        }
        return "";
    }
    
    private String captureTableName(String sql) {
        String bracket = "(";
        int fBracketPos = 0;
        fBracketPos = sql.indexOf(bracket);
        String preStr = sql.substring(0, fBracketPos);
        preStr = preStr.trim();
        
        preStr = preStr.toUpperCase();
        if (!preStr.contains("TABLE")) {
            throw new RuntimeException("末获取到表名称");
        }
        String[] words = preStr.split(" ");
        if (words.length > 0) {
            return words[words.length-1];
        }
        throw new RuntimeException("末获取到表名称");
    }
    
}
